<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Illuminate\Database\Events\QueryExecuted;

class QueryExecutedListener
{

    /**
     * Handle the event.
     */
    public function handle(QueryExecuted $event): void
    {
        if (config("app.debug") || ($event->time > 4000)) {
            $sql = $event->sql;
            $position = 0;
            foreach ($event->bindings as $value) {
                $position = strpos($sql, '?', $position);
                if ($position === false) {
                    break;
                }
                $value = "'{$value}'";
                $sql = substr_replace($sql, $value, $position, 1);
                $position += strlen($value);
            }
            Log::channel('sql')->info(sprintf('[%s][%s] %s', $event->connectionName, $event->time / 1000, $sql));
        }
    }
}
